<?php

namespace App\Http\Controllers\Backend;

use App\Http\Requests\Backend\StoreWechatGroup;
use App\Http\Resources\Backend\WechatGroupResource;
use App\Models\AdminLog;
use App\Models\WechatGroup;
use App\Services\WechatGroupService;
use Illuminate\Http\Request;

class WechatGroupController extends BackendController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 活动列表
     */
    public function index(Request $request)
    {
        $wechatGroups = WechatGroup::orderBy('created_at', 'desc')->nameLike($request->name)->paginate($request->size);
        return WechatGroupResource::collection($wechatGroups);
    }

    /**
     * @param StoreWechatGroup $request
     * @return WechatGroupResource
     * 新增菜单组
     */
    public function store(StoreWechatGroup $request)
    {
        $wechatGroup = WechatGroup::create($request->all());
        AdminLog::log('新增菜单组' . $wechatGroup->name);
        return new WechatGroupResource($wechatGroup);
    }

    /**
     * @param WechatGroup $wechatGroup
     * @return WechatGroupResource
     * @throws \Exception
     * 停用/启用 活动
     */
    public function update(WechatGroup $wechatGroup)
    {
        $wechatGroup = WechatGroupService::edit($wechatGroup);
        AdminLog::log('更新菜单组' . $wechatGroup->name);
        return new WechatGroupResource($wechatGroup);
    }

    /**
     * @param WechatGroup $wechatGroup
     * @return \Illuminate\Database\Eloquent\Collection
     * 返回该活动id下的菜单信息
     */
    public function show(WechatGroup $wechatGroup)
    {
        $data = $wechatGroup->wechatMenus()->orderBy('is_enable', 'desc')->orderBy('sort', 'asc')->get();
        foreach ($data as $v) {
            $v['sub_btn_count'] = $v->children->count();
        }
        return $data;
    }
}